package com.hzy.common.handler;

import com.hzy.common.R;
import io.vertx.core.Handler;
import io.vertx.core.eventbus.ReplyException;
import io.vertx.core.json.Json;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.HttpException;

/**
 * @author huangzhenyu
 * @date 2025/4/3 14:54
 */
public class FailureHandler implements Handler<RoutingContext> {

    @Override
    public void handle(RoutingContext ctx) {
        int statusCode;
        String reason = null;
        if (ctx.failure() != null) {
            reason =  ctx.failure().getMessage();
            if (ctx.failure() instanceof HttpException) {
                statusCode = ((HttpException) ctx.failure()).getStatusCode();
            } else if (ctx.failure() instanceof ReplyException) {
                statusCode = ((ReplyException) ctx.failure()).failureCode();
            } else {
                statusCode = 500;
            }
        } else {
            statusCode = 404;
            reason =  "Not Found";
        }
        ctx.response()
                .setStatusCode(statusCode)
                .end(Json.encode(R.error(statusCode, "Error: " + reason)));
    }
}
